package com.nari.ncps.screen.service.impl.wholeproduct;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.nari.ncps.screen.mapper.ne.NeOpermonRtPvMapper;
import com.nari.ncps.screen.mapper.ne.NeOpermonRtWindMapper;
import com.nari.ncps.screen.service.wholeproduct.IWholeNeRealTimePowerService;
import com.nari.ncps.screen.vo.wholeproduct.NewEnergyRealTimePowerVO;
import com.nari.ncps.screen.entity.ne.NeOpermonRtPv;
import com.nari.ncps.screen.entity.ne.NeOpermonRtWind;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 新能源实时功率 服务实现类
 * </p>
 *
 * @author xuesong
 * @since 2025-10-12
 */
@Service
public class WholeNeRealTimePowerServiceImpl implements IWholeNeRealTimePowerService {

    private final NeOpermonRtWindMapper windMapper;
    private final NeOpermonRtPvMapper pvMapper;

    public WholeNeRealTimePowerServiceImpl(NeOpermonRtWindMapper windMapper, 
                                          NeOpermonRtPvMapper pvMapper) {
        this.windMapper = windMapper;
        this.pvMapper = pvMapper;
    }

    @Override
    public List<NewEnergyRealTimePowerVO> getNewEnergyRealTimePower(Integer year) {
        // 1. 查询风电数据
        QueryWrapper<NeOpermonRtWind> windQueryWrapper = new QueryWrapper<>();
        if (year != null) {
            windQueryWrapper.eq("year", year);
        }
        windQueryWrapper.orderByDesc("date", "hour", "minute").last("LIMIT 20");
        List<NeOpermonRtWind> windList = windMapper.selectList(windQueryWrapper);
        
        // 2. 查询光伏数据
        QueryWrapper<NeOpermonRtPv> pvQueryWrapper = new QueryWrapper<>();
        if (year != null) {
            pvQueryWrapper.eq("year", year);
        }
        pvQueryWrapper.orderByDesc("date", "hour", "minute").last("LIMIT 20");
        List<NeOpermonRtPv> pvList = pvMapper.selectList(pvQueryWrapper);
        
        // 3. 将风电数据转换为Map，以时间为key
        Map<String, NeOpermonRtWind> windMap = windList.stream()
            .collect(Collectors.toMap(
                this::buildTimeKey, 
                wind -> wind,
                (existing, replacement) -> existing
            ));
        
        // 4. 将光伏数据转换为Map，以时间为key
        Map<String, NeOpermonRtPv> pvMap = pvList.stream()
            .collect(Collectors.toMap(
                this::buildTimeKey, 
                pv -> pv,
                (existing, replacement) -> existing
            ));
        
        // 5. 获取所有时间点（取两者的并集）
        Set<String> allTimeKeys = new HashSet<>();
        allTimeKeys.addAll(windMap.keySet());
        allTimeKeys.addAll(pvMap.keySet());
        
        // 6. 合并数据
        List<NewEnergyRealTimePowerVO> resultList = new ArrayList<>();
        for (String timeKey : allTimeKeys) {
            NewEnergyRealTimePowerVO vo = new NewEnergyRealTimePowerVO();
            
            NeOpermonRtWind wind = windMap.get(timeKey);
            NeOpermonRtPv pv = pvMap.get(timeKey);
            
            // 优先使用风电或光伏的时间信息
            if (wind != null) {
                vo.setYear(wind.getYear());
                vo.setMonth(wind.getMonth());
                vo.setDay(wind.getDay());
                vo.setDate(wind.getDate());
                vo.setHour(wind.getHour() != null ? wind.getHour().intValue() : null);
                vo.setMinute(wind.getMinute() != null ? wind.getMinute().intValue() : null);
                vo.setWindRealtimePower(wind.getRealtimePower());
            } else if (pv != null) {
                vo.setYear(pv.getYear());
                vo.setMonth(pv.getMonth());
                vo.setDay(pv.getDay());
                vo.setDate(pv.getDate());
                vo.setHour(pv.getHour() != null ? pv.getHour().intValue() : null);
                vo.setMinute(pv.getMinute() != null ? pv.getMinute().intValue() : null);
            }
            
            // 设置风电功率
            BigDecimal windPower = (wind != null && wind.getRealtimePower() != null) 
                ? wind.getRealtimePower() 
                : BigDecimal.ZERO;
            vo.setWindRealtimePower(windPower);
            
            // 设置光伏功率
            BigDecimal pvPower = (pv != null && pv.getRealtimePower() != null) 
                ? pv.getRealtimePower() 
                : BigDecimal.ZERO;
            vo.setPvRealtimePower(pvPower);
            
            // 计算总功率
            BigDecimal totalPower = windPower.add(pvPower);
            vo.setTotalRealtimePower(totalPower);
            
            resultList.add(vo);
        }
        
        // 7. 按时间倒序排序
        resultList.sort((a, b) -> {
            if (a.getDate() != null && b.getDate() != null) {
                int dateCompare = b.getDate().compareTo(a.getDate());
                if (dateCompare != 0) return dateCompare;
            }
            
            if (a.getHour() != null && b.getHour() != null) {
                int hourCompare = b.getHour().compareTo(a.getHour());
                if (hourCompare != 0) return hourCompare;
            }
            
            if (a.getMinute() != null && b.getMinute() != null) {
                return b.getMinute().compareTo(a.getMinute());
            }
            
            return 0;
        });
        
        // 8. 取前20条
        return resultList.stream().limit(20).collect(Collectors.toList());
    }
    
    /**
     * 构建时间key
     */
    private String buildTimeKey(NeOpermonRtWind wind) {
        return String.format("%d-%d-%d-%d-%d", 
            wind.getYear(), wind.getMonth(), wind.getDay(), 
            wind.getHour(), wind.getMinute());
    }
    
    /**
     * 构建时间key
     */
    private String buildTimeKey(NeOpermonRtPv pv) {
        return String.format("%d-%d-%d-%d-%d", 
            pv.getYear(), pv.getMonth(), pv.getDay(), 
            pv.getHour(), pv.getMinute());
    }
}

